<template>
    <div class="edit-container">
        <el-steps :active="curStep" align-center>
            <el-step
                    style="cursor: pointer"
                    v-for="(n, i) in steps"
                    :key="n.key"
                    :title="n.title"
                    @click.stop="changeStep(i)"
            ></el-step>
        </el-steps>
        <div class="body">
            <!-- <transition name="fade" mode="out-in" appear> -->
            <Suspense>
                <template #default>
                    <div v-for="item in steps" :key="`${item.key}`">
                        <component
                                v-if="steps[curStep].key === item.key"
                                :is="`step-${item.name}`"
                                ref="child"
                        />
                    </div>
                </template>
                <template #fallback>
                    <div>Loading...</div>
                </template>
            </Suspense>
            <!-- </transition> -->
        </div>
        <div class="footer" ref="footerRef">
            <el-button v-if="showCsBtn">重置</el-button>
            <el-button v-if="showCsBtn" type="primary" @click="showCsLog">查看测试日志</el-button>
            <el-button v-if="showCsBtn" type="primary" @click="handleCs">下发测试</el-button>
            <el-button v-if="showCsBtn">停止测试</el-button>
            <el-button @click="onClose">关闭</el-button>
            <el-button
                    v-show="curStep === 0 && dialogStatus === 'add'"
                    @click="onBack"
            >返回
            </el-button
            >
            <el-button v-show="curStep !== 0" @click="onPre">上一步</el-button>
            <el-button v-show="handleSaveShow" type="primary" @click="onNext('save')"
            >暂存
            </el-button
            >
            <el-button
                    v-if="curStep !== steps.length - 1"
                    type="primary"
                    @click="onNext('next')"
            >下一步
            </el-button
            >
            <el-button
                    v-show="curStep === steps.length - 1"
                    type="primary"
                    @click="handleRelease"
            >发布
            </el-button
            >
        </div>

        <el-dialog
                width="60%"
                title="日志内容"
                v-model="logDetailVisible"
                @close="hideMoreCsLog"
                :close-on-click-modal="false"
                :close-on-press-escape="false">
            <div class="log-detail" v-html="csLogParams.logContent">
            </div>
            <span slot="footer" class="dialog-footer" style="margin-top:10px;">
              <el-button type="primary" v-if="!csLogParams.end" @click="showMoreCsLog()">下一页</el-button>
              <el-button type="primary" class="m-l-10px" @click="hideMoreCsLog()">关闭</el-button>
            </span>
        </el-dialog>

    </div>


</template>

<script>
import {serviceStore} from '@slc/store/service';
import {flowServiceStore} from '@slc/store/flowService';
import {mapActions, mapState} from 'pinia';
import {ElMessage as Message} from 'element-plus'
import { Base64 } from 'js-base64';

// import { mapActions, mapMutations, mapState } from 'vuex'
import {
    publishService,
    submitService,
    saveNLBP,
    saveExpertDsl,
    saveScript,
    checkService,
    updateVersionConfig,
    searchCsLog
} from '@slc/api/slc/inventory'
// import StepZhpz from './step-zhpz.vue'
// import StepXzapi from './step-xzapi.vue'
// import StepXzsjj from './step-xzsjj.vue'
// import StepPzxx from './step-pzxx.vue'
// import StepQqt from './step-qqt.vue'
// import StepSrcs from './step-srcs.vue'
// import StepSccs from './step-sccs.vue'
// import StepCs from './step-cs.vue'
// import StepCsfb from './step-csfb.vue'
// import StepExpert from './step-expert.vue'
// import StepNlgz from './step-nlgz.vue'
// import StepSjnlgz from './step-sjnlgz.vue'
// import StepXynlgz from './step-xynlgz.vue'
import {defineAsyncComponent} from 'vue';

export default {
    components: {
        // StepZhpz,
        // StepXzapi,
        // StepXzsjj,
        // StepPzxx,
        // StepQqt,
        // StepSrcs,
        // StepSccs,
        // StepCs,
        // StepCsfb,
        // StepExpert,
        // StepNlgz,
        // StepSjnlgz,
        // StepXynlgz

        StepZhpz: defineAsyncComponent(() => import('./step-zhpz.vue')),
        StepXzapi: defineAsyncComponent(() => import('./step-xzapi.vue')),
        StepXzsjj: defineAsyncComponent(() => import('./step-xzsjj.vue')),
        StepPzxx: defineAsyncComponent(() => import('./step-pzxx.vue')),
        StepQqt: defineAsyncComponent(() => import('./step-qqt.vue')),
        StepSrcs: defineAsyncComponent(() => import('./step-srcs.vue')),
        StepSccs: defineAsyncComponent(() => import('./step-sccs.vue')),
        StepCsfb: defineAsyncComponent(() => import('./step-csfb.vue')),
        StepExpert: defineAsyncComponent(() => import('./step-expert.vue')),
        StepCs: defineAsyncComponent(() => import('./step-cs.vue')),
        StepNlgz: defineAsyncComponent(() => import('./step-nlgz.vue')),
        StepSjnlgz: defineAsyncComponent(() => import('./step-sjnlgz.vue')),
        StepXynlgz: defineAsyncComponent(() => import('./step-xynlgz.vue')),

    },
    data() {
        return {
            logDetailVisible: false,
            csLogParams: {
                end: true,
                serviceVerId: '',
                fromLineNum: 1,
                lineNum: 1000,
            }
        }
    },
    // ExpertCapability: () => import("./expert-capability.vue"),
    // StepNlbp: () => import('./step-nlbp.vue'),
    computed: {
        ...mapState(serviceStore, [
            'dialogStatus',
            'serverReleaseType',
            'steps',
            'curStep',
            'maxStep',
            'zhpzInfo',
            'pzxxInfo',
            'qqtInfo',
            'chooseApiInfo',
            'chooseSjjInfo',
            'inputData',
            'serviceVerId',
            'csInfo',
            'reqHeaderList',
            'inputData'
        ]),
        ...mapState(flowServiceStore, [
            'graph',
            'moreNodeInfo',
            'serviceDomain',
            'serviceTextArea',
            'scriptType'
        ]),
        handleSaveShow() {
            const pzxxIndex = this.steps.findIndex((n) => n.key === 'PZXX')
            return this.curStep >= pzxxIndex
        },
        pzxxIndex() {
            return this.steps.findIndex((n) => n.key === 'PZXX')
        },
        showCsBtn() {
            // 展示测试专属按钮
            return this.steps.findIndex((n) => n.key === 'CS') === this.curStep
        },

    },
    methods: {
        ...mapActions(serviceStore, [
            'setVisible',
            'setVersionVisible',
            'setCurStep',
            'setMaxStep',
            'doClear',
            'setCsInfo',
            'doSavePzxxProtocol',
            'doSaveSrcsOrSccsProtocol'
        ]),
        showCsLog() {
            this.csLogParams = {
                serviceVerId: this.serviceVerId,
                fromLineNum: 1,
                lineNum: 1000,
            }
            searchCsLog(this.csLogParams).then(res => {
                if (res) {
                    const {data} = res;
                    this.csLogParams.logContent = data.logContent;
                    this.csLogParams.end = data.end;
                    this.logDetailVisible = true;

                }

            })
        },
        hideMoreCsLog() {
            this.logDetailVisible = false;
        },
        showMoreCsLog() {
            searchCsLog(this.csLogParams).then(res => {
                if (res) {
                    const {data} = res;
                    this.csLogParams.logContent += data.logContent;
                    this.csLogParams.fromLineNum =  data.toLineNum;
                    this.csLogParams.end = data.end;
                }

            })

        },
        async handleCs() {
            const params = {}
            const qqtHeaders = {}
            this.reqHeaderList.map(n => {
                qqtHeaders[n.nodeName] = n.nodeData
            })
            this.inputData.map(n => {
                params[n.nodeName] = n.nodeData
            })

            try {
                const res = await checkService(params, qqtHeaders, this.serviceVerId);
                this.setCsInfo(res);
                if (res.code === '200') {
                    this.setCsInfo({
                        ...this.csInfo,
                        nextFlag: true
                    })
                }
                // 处理成功的响应
            } catch (error) {
                const errorMessage = error.message; // 获取错误信息
                console.log(error);
                this.setCsInfo(error);
            }

        },
        changeStep(i) {
            // 如果保存过配置，返回了serviceVerId,则不能回到配置之前的步骤
            if (this.serviceVerId && i < this.pzxxIndex) {
                Message.error('数据已保存，不可以修改！')
                return
            }
            if (i <= this.maxStep) {
                this.setCurStep(i)
                this.setMaxStep(i)
            }
        },
        onBack() {
            this.doClear()
        },
        onPre() {
            let step = this.curStep
            // 如果保存过配置，返回了serviceVerId,则不能回到配置之前的步骤
            if (this.serviceVerId && step <= this.pzxxIndex) {
                Message.error('数据已保存，不可以修改！')
                return
            }
            step -= 1
            this.setCurStep(step)
        },
        async onNext(key) {
            if (key === 'save' && this.steps[this.curStep].key === 'CSFB') {
                this.onClose()
                return
            }
            if (key === 'save' && this.steps[this.curStep].key === 'CS') {
                this.onClose()
                return
            }
            if (this.steps[this.curStep].key === 'XZAPI') {
                if (JSON.stringify(this.chooseApiInfo) === '{}') {
                    Message.error('请选择API ！')
                    return
                }
                this.handleStepAdd()
            } else if (this.steps[this.curStep].key === 'XZSJJ') {
                if (JSON.stringify(this.chooseSjjInfo) === '{}') {
                    Message.error('请选择数据集 ！')
                    return
                }
                this.handleStepAdd()
            } else if (this.steps[this.curStep].key === 'PZXX') {
                if (!this.pzxxInfo.serviceName) {
                    Message.error('请输入能力名称！')
                    return
                }
                if (!this.pzxxInfo.servicePath) {
                    Message.error('请输入能力别名！')
                    return
                }
                if (this.pzxxInfo.cateIds.length === 0) {
                    Message.error('请选择所属分类！')
                    return
                }
                if (!this.pzxxInfo.serviceDesc) {
                    Message.error('请输入能力描述！')
                    return
                }
                await this.doSavePzxxProtocol()
                if (this.serviceVerId)
                    this.handleStepAdd()
            } else if (this.steps[this.curStep].key === 'QQT') {
                const {isHeaderInChange, isHeaderOutChange} = this.qqtInfo
                if (this.serverReleaseType === '3') {
                    const res = await updateVersionConfig({
                        serviceVerId: this.serviceVerId,
                        isHeaderInChange: isHeaderInChange ? 'Y' : 'N',
                        isHeaderOutChange: isHeaderOutChange ? 'Y' : 'N'
                    })
                    res.code === '200' && this.handleStepAdd()
                } else {
                    this.handleStepAdd()
                }
            } else if (this.steps[this.curStep].key == 'NLBP') {
                const params = {
                    serviceVerId: this.serviceVerId,
                    contentText: JSON.stringify(this.handleNlbpSaveData())
                }
                const res = await saveNLBP(params)
                if (res.code === '200') {
                    this.handleStepAdd()
                }
            } else if (
                this.steps[this.curStep].key === 'SRCS' ||
                this.steps[this.curStep].key === 'SCCS' || this.steps[this.curStep].key === 'XYNLGZ'
            ) {
                if (this.serverReleaseType === '2' || this.serverReleaseType === '3') {
                    let params
                    if (this.steps[this.curStep].key === 'SRCS') {
                        params = {
                            serviceVerId: this.serviceVerId,
                            isParamInChange: this.zhpzInfo.isParamInChange ? 'Y' : 'N',
                            inparamWithAttr: this.zhpzInfo.inparamWithAttr ? 'Y' : 'N'
                        }
                    } else if (this.steps[this.curStep].key === 'SCCS') {
                        params = {
                            serviceVerId: this.serviceVerId,
                            isParamOutChange: this.zhpzInfo.isParamOutChange ? 'Y' : 'N',
                            outparamWithAttr: this.zhpzInfo.outparamWithAttr ? 'Y' : 'N'
                        }
                    } else if (this.steps[this.curStep].key === 'XYNLGZ') {
                        const {isHeaderInChange, isHeaderOutChange} = this.qqtInfo
                        params = {
                            serviceVerId: this.serviceVerId,
                            isParamInChange: this.zhpzInfo.isParamInChange ? 'Y' : 'N',
                            inparamWithAttr: this.zhpzInfo.inparamWithAttr ? 'Y' : 'N',
                            isParamOutChange: this.zhpzInfo.isParamOutChange ? 'Y' : 'N',
                            outparamWithAttr: this.zhpzInfo.outparamWithAttr ? 'Y' : 'N',
                            isHeaderInChange: isHeaderInChange ? 'Y' : 'N',
                            isHeaderOutChange: isHeaderOutChange ? 'Y' : 'N'
                        }
                    }
                    await updateVersionConfig(params)
                    await this.doSaveSrcsOrSccsProtocol()
                }
                this.handleStepAdd()
            } else if (this.steps[this.curStep].key == 'NLGZ') {
                const params = {
                    serviceVerId: this.serviceVerId,
                    contentText:this.serviceTextArea.startsWith('base64:') ? this.serviceTextArea : 'base64:'+ Base64.encode(this.serviceTextArea),
                    scriptType: this.scriptType //1:java
                }

                if(key === 'save'){
                    params['operateType'] ='tempStore'
                }


                const res = await saveScript(params)
                if (res.code === '200') {
                    this.handleStepAdd()
                }
            } else if (this.steps[this.curStep].key == 'EXPERT') {
                const params = {
                    serviceVerId: this.serviceVerId,
                    contentText: this.serviceTextArea
                }
                const res = await saveExpertDsl(params)
                if (res.code === '200') {
                    this.handleStepAdd()
                }
            } else if (this.steps[this.curStep].key == 'CS') {
                if (!this.csInfo.nextFlag) {
                    return Message.error('下发测试失败，无法进入下一步！'), !1
                }
                this.handleStepAdd()
            } else {
                this.handleStepAdd()
            }
            if (key === 'save') {
                this.onClose()
            }
        },
        handleStepAdd() {
            let step = this.curStep
            let mStep = this.maxStep
            step += 1
            this.setCurStep(step)
            if (step > mStep) {
                this.setMaxStep(step)
            }
        },
        onClose() {
            this.setVisible(false)
            this.setVersionVisible(false)
        },

        // 发布
        async handleRelease() {
            const res = await publishService({serviceVerId: this.serviceVerId})
            if (res.code === '200') {
                Message.success('发布成功！')
                this.onClose()
            }
        },
        async onSubmit() {
            const res = await submitService({serviceVerId: this.serviceVerId})
            if (res.code === '200') {
                Message.success('提交审核成功！')
                this.onClose()
            }
        },
        handleNlbpSaveData() {
            this.graph.getCells().forEach((cell) => {
                cell.removeTools()
            })
            let graphData = this.graph.toJSON()
            graphData.cells = graphData.cells.map((n) => {
                let type
                if (n.shape === 'edge') {
                    type = 'line'
                } else {
                    type = n.data ? n.data.type : ''
                }
                let obj = {}
                if (type === 'from-rest') {
                    obj = {
                        http_method: this.serviceDomain.httpRequestMethod
                    }
                }
                if (this.moreNodeInfo[n.id]) {
                    if (type === 'controller-multicast') {
                        obj = {
                            parallel_processing: this.moreNodeInfo[n.id].parallel_processing, // 【必传，boolean】并行分发
                            stop_on_exception: this.moreNodeInfo[n.id].stop_on_exception, // 【必传，boolean】异常停止，仅串行时生效
                            timeout: this.moreNodeInfo[n.id].timeout // 【必传，int】 超时(毫秒)
                        }
                    } else if (type === 'processor-JsonToSoapXml') {
                        const soapNode =
                            this.moreNodeInfo[this.moreNodeInfo[n.id].soapId] || {}
                        obj = {
                            soap_wsdl_url: soapNode.apiUrl, //【必传，string】WSDL路径
                            soap_operation: soapNode.httpRequestMethod, //【必传，string】WSDL中请求方法,
                            xml_node_xpath: this.moreNodeInfo[n.id].paramInSerializeName, //【可空，string】入参名称
                            param_serialize: this.moreNodeInfo[n.id].isParamSerialize, //【必传，boolean】参数是否序列化
                            soap_direction: this.moreNodeInfo[n.id].soap_direction
                        }
                    } else if (type === 'to-soap') {
                        obj = {
                            endpoint_url: this.moreNodeInfo[n.id].apiUrl, //【必传，string】API接口服务地址
                            soap_wsdl_url: this.moreNodeInfo[n.id].apiUrl, //【必传，string】API接口服务WSDL地址
                            target_auth_type: this.moreNodeInfo[n.id].targetAuthType, //【必传，string】API接口认证方式
                            app_id: this.moreNodeInfo[n.id].appId //【必传，string】API接口所属应用ID
                        }
                    } else if (type === 'processor-SoapXmlToJson') {
                        const soapNode =
                            this.moreNodeInfo[this.moreNodeInfo[n.id].soapId] || {}
                        obj = {
                            soap_operation: soapNode.apiUrl, //【必传，string】请求方法
                            xml_node_xpath: this.moreNodeInfo[n.id].paramOutSerializeName, //【必传，string】出参名称
                            body_with_attr: this.moreNodeInfo[n.id].outparamWithAttr, //【必传，string】参数是否带属性
                            soap_direction: this.moreNodeInfo[n.id].soap_direction
                        }
                    } else if (type === 'to-rest') {
                        obj = {
                            endpoint_url: this.moreNodeInfo[n.id].mockUrl, //【必传，string】API接口服务地址
                            target_auth_type: this.moreNodeInfo[n.id].targetAuthType, //【必传，string】API接口认证方式
                            app_id: this.moreNodeInfo[n.id].appId //【必传，string】API接口所属应用ID
                        }
                    } else if (type === 'to-jms') {
                        obj = {
                            queue_name: this.moreNodeInfo[n.id].queue_name //【必传，string】队列名称
                        }
                    } else if (type === 'to-dataset') {
                        obj = {
                            sql: this.moreNodeInfo[n.id].sql, //【必传，string】查询SQL语句
                            datasource: this.moreNodeInfo[n.id].datasource ////【必传，string】队列名称数据源名称
                        }
                    } else if (type === 'processor-RawToFormData') {
                        const nextNode =
                            this.graph.getNeighbors(this.graph.getCellById(n.id))[0] || {}
                        let http_method = ''
                        if (nextNode.id) {
                            http_method = this.moreNodeInfo[nextNode.id].httpRequestMethod
                        }
                        obj = {
                            http_method //【必传，string】请求方式
                        }
                    } else if (type === 'processor-ParamBuilderJson') {
                        const nextNode =
                            this.moreNodeInfo[this.moreNodeInfo[n.id].nextId] || {}
                        obj = {
                            paramOut: nextNode.inParamList //【必传，string】请求方式
                        }
                    } else if (type === 'line') {
                        obj = {
                            isDefault: this.moreNodeInfo[n.id].isDefault, //【必填，boolean】是否默认分支
                            rule: this.moreNodeInfo[n.id].isDefault
                                ? '<otherwise/>'
                                : this.moreNodeInfo[n.id].rule //【可选，string】条件表达式
                        }
                    }
                }
                n.form = {
                    type,
                    data: {
                        ...obj
                    }
                }
                return n
            })
            return {
                properties: {
                    serviceDomain: this.serviceDomain,
                    moreNodeInfo: this.moreNodeInfo
                },
                ...graphData
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.el-button--primary:focus {
  background: #1890ff;
  border-color: #1890ff;
}

.edit-container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .body {
    margin: 16px 0;
    flex: 1;
  }

  .footer {
    display: flex;
    justify-content: flex-end;
  }

  .log-detail {
    // height: calc(100%-80px);
    overflow: auto;
    white-space: pre-wrap;
    height: 600px;
  }


}


</style>
